package middleware

import (
	"app/internal/consts"
	"app/pkg/jwt"
	"errors"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	j "github.com/golang-jwt/jwt/v5"
)

// Hack 模拟某个用户的身份
func Hack(user_id int) func(c *gin.Context) {
	return func(c *gin.Context) {
		c.Set(consts.USER_ID, user_id)
		c.Next()
	}
}

// LoginRequired 必须登录才能访问
func LoginRequired() func(c *gin.Context) {
	return func(c *gin.Context) {
		//从上下文中获取用户id
		user_id := c.GetInt(consts.USER_ID)
		//如果获取不到用户就表明未登录
		if user_id == 0 {
			//TODO 处理为标准响应
			c.AbortWithStatus(http.StatusForbidden)
			return
		}
		c.Next()
	}
}

// SinglePoint 单点登录控制
func SinglePoint(user_id int) func(c *gin.Context) {
	return func(c *gin.Context) {
		//TODO 单点登录控制逻辑
		c.Next()
	}
}

// JwtTokenCheck 检查jwt访问凭证
func JwtTokenCheck() func(c *gin.Context) {
	return func(c *gin.Context) {
		//已经登录的用户不需要检查，用于Hack登录的场景
		if c.GetInt(consts.USER_ID) > 0 {
			c.Next()
			return
		}
		authorization := c.GetHeader("Authorization")
		//如果携带的 Authorization 不合法
		if authorization == "" || !strings.HasPrefix(authorization, "Bearer ") {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		//str, err := jwt.New().TokenGeneration(11)
		claim, err := jwt.New().TokenParse(authorization[7:])
		//token解析出错
		if err != nil {
			//TODO 处理为标准响应
			if errors.Is(err, j.ErrTokenExpired) {
				// token过期的报错
			}
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		c.Set(consts.USER_ID, claim.Id)

		c.Next()
	}
}

// CustomerToken 自定义token验证,如果带的token不同就不能通过
func CustomerToken(token string) func(c *gin.Context) {
	return func(c *gin.Context) {
		t := c.GetHeader("Token")
		if t != token {
			c.AbortWithStatus(403)
			return
		}
		c.Next()
	}
}
